import { GM_xmlhttpRequest } from 'vite-plugin-monkey/dist/client'

export const $GM_http_post = (url: string, body = {}, headers = {}) => {

  let data = typeof body === 'object' ? JSON.stringify(body) : ""

  return new Promise<string>((resolve, reject) => {
    GM_xmlhttpRequest({
      method: 'POST',
      url: url,
      headers: headers,
      data: data,
      onload: (response) => {
        try {
          const res = response.responseText
          resolve(res)
        } catch (e) {
          reject(e)
        }
      },
      onerror: (error) => {
        reject(error)
      }
    })
  })
}

export const $GM_http_get = (url: string, headers = {}) => {
  return new Promise<string>((resolve, reject) => {
    GM_xmlhttpRequest({
      method: 'GET',
      url: url,
      headers: headers,
      onload: (response) => {
        try {
          const res = response.responseText
          resolve(res)
        } catch (e) {
          reject(e)
        }
      },
      onerror: (error) => {
        reject(error)
      }
    })
  })
}